import { View, Image } from '@tarojs/components';
import { useEffect, useState } from 'react';
import { AtCurtain } from 'taro-ui';
import { checkAuth } from '@/utils/authUtil';
import Taro from '@tarojs/taro';
import { sendClickData } from '@/service/apis/home/index';
import globalStore from '@/store/global';
import { BannerJumpType } from '../../constants';
import './index.scss';

export default function ({ show, onClose, popupList = [] }: any) {
  const [cloesedData, setClosedData]: any = useState([]);
  const [currentImage, setCurrentImage] = useState({
    url: '',
    id: 0,
    type: '',
    type_value: '',
    name: '',
  });
  const _onClose = () => {
    let _closedData = cloesedData;
    if (!_closedData.includes(currentImage.id)) {
      _closedData.push(currentImage.id);
    }
    setClosedData(_closedData);
    if (popupList.length === _closedData.length) {
      onClose && onClose();
    } else {
      const otherList = popupList.filter((item) => !_closedData.includes(item.id));
      if (otherList.length > 0) {
        setCurrentImage(otherList[0]);
      }
    }
  };
  useEffect(() => {
    if (popupList.length > 0) {
      setCurrentImage(popupList[0]);
    }
  }, [popupList]);

  const onJump = () => {
    const { type, type_value, id } = currentImage;
    sendClickData({
      ad_id: id,
    });
    switch (type) {
      // 商品
      case BannerJumpType.Product: {
        Taro.navigateTo({
          // url: `/pages/goods/detail/index?id=${type_value}`,
          url: `/pages/contrast/detail/index?goods_sn=${type_value}&lat=${globalStore.currentShop.lat}&lng=${globalStore.currentShop.lng}&type=product`,
        });
        break;
      }
      // 服务
      case BannerJumpType.Service: {
        Taro.navigateTo({
          // url: `/subPages/service/detail/index?id=${type_value}`,
          url: `/pages/contrast/detail/index?goods_sn=${type_value}&lat=${globalStore.currentShop.lat}&lng=${globalStore.currentShop.lng}&type=service`,
        });
        break;
      }
      // 活动
      case BannerJumpType.Activity: {
        checkAuth(() => {
          Taro.navigateTo({
            url: `/subPages/myActivity/detail/index?topic_id=${type_value}`,
          });
        });
        break;
      }
      // 外链
      case BannerJumpType.Url: {
        Taro.navigateTo({
          url: `/pages/webview/index?url=${type_value}`,
        });
        break;
      }
      // 购买会员
      case BannerJumpType.Vip: {
        Taro.navigateTo({
          url: `/subPages/vipCardDetail/index`,
        });
        break;
      }
    }
  };
  return (
    <View className="home-popup">
      <AtCurtain isOpened={show} onClose={_onClose}>
        <Image style="width:100%;height:250px" onClick={onJump} src={currentImage.url} />
      </AtCurtain>
    </View>
  );
}
